<template>
  <div>
    <div>
      <el-collapse
        v-model="activeName"
        accordion
      >
        <el-collapse-item name="1">
          <template slot="title">
            节点设置<i class="header-icon el-icon-info" />
          </template>
          <div>
            <el-form
              :inline="true"
              label-width="100px"
              size="small"
            >
              <el-form-item label="编号">
                <el-input
                  v-model="id"
                  disabled
                />
              </el-form-item>
              <el-form-item
                label="名称"
                required
              >
                <el-input v-model="name" />
              </el-form-item>
              <el-form-item label="优先级">
                <el-input
                  v-model="priority"
                  type="number"
                />
              </el-form-item>
              <el-form-item label="文档">
                <el-input
                  v-model="documentation"
                  type="textarea"
                  @change="updateDocumentation($event)"
                />
              </el-form-item>
            </el-form>
          </div>
        </el-collapse-item>
        <el-collapse-item name="2">
          <template slot="title">
            人员设置<i class="header-icon el-icon-info" />
          </template>
          <div>
            <el-form
              :inline="true"
              label-width="100px"
              size="small"
            >
              <el-form-item label="人员类型">
                <el-radio-group v-model="assigneeType">
                  <el-radio-button label="1">前端指定</el-radio-button>
                  <el-radio-button label="0">配置</el-radio-button>
                  <el-radio-button label="2">同前节点</el-radio-button>
                </el-radio-group>
              </el-form-item>
              <el-form-item
                v-if="assigneeType === '2'"
                label="依赖节点"
              >
                <el-select
                  v-model="relationNodeId"
                  filterable
                  placeholder="请选择"
                >
                  <el-option
                    v-for="item in userTaskList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="地区" v-if="assigneeType!='2'">
                <el-tree-select :props="props" :options="areaList" :value="area"
                :clearable="isClearable" :accordion="isAccordion"  @getValue="getAreaValue($event)">
                </el-tree-select>
              </el-form-item>
              <el-form-item label="部门" v-if="assigneeType!='2'">
                <el-tree-select :props="props" :options="departmentList" :value="department"
                :clearable="isClearable" :accordion="isAccordion"  @getValue="getDeptValue($event)">
                </el-tree-select>
              </el-form-item>
              <el-form-item label="角色" v-if="assigneeType!='2'">
                <el-select v-model="role" filterable placeholder="请选择" multiple>
                  <el-option
                    v-for=" p in roleList"
                    :key="p.code"
                    :label="p.name"
                    :value="p.code"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="角色关系" v-if="assigneeType!='2'">
                <el-switch
                  v-model="roleIsAnd"
                  active-text="交集"
                  inactive-text="并集" />
              </el-form-item>
              <el-form-item label="用户类型" v-if="assigneeType!='2'">
                <el-select v-model="userType" placeholder="请选择">
                  <el-option key="1" label="政府" value="1"/>
                  <el-option key="2" label="企业" value="2"/>
                </el-select>
              </el-form-item>
              <el-form-item label="规则" v-if="assigneeType!='2'">
                <el-select v-model="rule" filterable placeholder="请选择">
                  <el-option
                    v-for=" p in ruleList"
                    :key="p.code"
                    :label="p.name"
                    :value="p.code"
                  />
                </el-select>
              </el-form-item>
            </el-form>
          </div>
        </el-collapse-item>
        <el-collapse-item name="3">
          <template slot="title">
            节点表单<i class="header-icon el-icon-info" />
          </template>
          <div>
            <el-form
              :inline="true"
              label-width="100px"
              size="small"
            >
              <el-form-item label="表单标识">
                <el-input v-model="selectFormKey"/>
                <el-button
                  type="success"
                  size="small"
                  @click="showSelectDialog()"
                >选择</el-button>
              </el-form-item>
              <el-input
                v-if="false"
                v-model="formKey"
              />
            </el-form>
          </div>
        </el-collapse-item>

        <el-collapse-item name="4">
          <template slot="title">
            节点属性<i class="header-icon el-icon-info" />
          </template>
          <div>
            <el-form
              :inline="true"
              label-width="120px"
              size="small"
            >
              <el-form-item
                label="执行限时(分钟)"
                required
              >
                <el-input-number v-model="executeTimeLimit" :min="0"/>
              </el-form-item>
              <el-form-item
                label="通过比例"
                required
              >
                <el-select
                  v-model="proportion"
                  placeholder="请选择"
                >
                  <el-option
                    v-for="item in proportionOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>

              <el-form-item
                label="任务类型"
                required
              >
                <el-radio-group v-model="taskType">
                  <el-radio label="start">发起</el-radio>
                  <el-radio label="approve">审批</el-radio>
                </el-radio-group>
              </el-form-item>

              <el-form-item
                label="节点按钮"
                required
              >
                <el-checkbox-group
                  v-model="actionList"
                  @change="handleChange"
                >
                  <el-checkbox
                    v-for="item in actionTypeList"
                    :key="item.value"
                    :label="item.value"
                  >{{ item.label }}</el-checkbox>
                </el-checkbox-group>
              </el-form-item>
            </el-form>
          </div>
        </el-collapse-item>
        <el-collapse-item name="5">
          <template slot="title">
            节点事件<i class="header-icon el-icon-info" />
          </template>
          <div>TODO</div>
        </el-collapse-item>
      </el-collapse>

    </div>

    <div>
      <el-dialog
        :title="selectFormDialog.title"
        :visible.sync="selectFormDialog.visible"
        :width="selectFormDialog.width"
        :fullscreen="selectFormDialog.fullscreen"
        :close-on-press-escape="selectFormDialog.closeOnPressEscape"
        append-to-body
        center
        :before-close="handleClose"
        @close="closeSelectFormDialog"
      >
        <!-- <selectForm
          ref="selectForm"
          @setForm="setForm"
        /> -->
        <!-- TODO 待实现 -->
      </el-dialog>
    </div>
  </div>
</template>
<script>
import bpmnHelper from '../../js/helper/BpmnHelper'
import elementHelper from '../../js/helper/ElementHelper'
import elTreeSelect from '../../element'

// 用户任务属性组件
export default {
  components: { elTreeSelect },
  props: ['element'],
  inject: ['bpmnModeler'],
  data() {
    return {
      isClearable: true, // 可清空（可选）
      isAccordion: true, // 可收起（可选）
      props: {
        // 配置项（必选）
        value: 'value',
        label: 'label',
        children: 'children'
      },
      modeling: null,
      id: this.element.id || '',
      name: '',
      formKey: '',
      formName: '',
      selectFormKey: '',
      documentation: '',
      positions: [],
      priority: '1',
      candidateGroups: '没有受让人',
      selectFormDialog: {
        title: '选择表单',
        visible: false,
        width: '850',
        name: '选择表单', // 组件名,
        loading: false,
        fullscreen: false,
        closeOnPressEscape: false
      },
      assigneeType: '0', // 人员类型 0配置 1前端指定 2同前节点
      area: null,
      areaList: [], // 区域列表
      department: null,
      departmentList: [], // 部门列表
      role: null,
      roleList: [], // 角色列表
      roleIsAnd: true,
      userType: null, // 用户类型
      rule: null,
      ruleList: [], // 规则列表
      activeName: '1',
      proportionOptions: [
        {
          value: '0',
          label: '0%'
        },
        {
          value: '10',
          label: '10%'
        },
        {
          value: '20',
          label: '20%'
        },
        {
          value: '30',
          label: '30%'
        },
        {
          value: '40',
          label: '40%'
        },
        {
          value: '50',
          label: '50%'
        },
        {
          value: '60',
          label: '60%'
        },
        {
          value: '70',
          label: '70%'
        },
        {
          value: '80',
          label: '80%'
        },
        {
          value: '90',
          label: '90%'
        },
        {
          value: '100',
          label: '100%'
        }
      ],
      proportion: '100',
      taskType: 'approve',
      actionList: ['pass', 'reject'],
      actionTypeList: [
        {
          value: 'start',
          label: '发起'
        },
        {
          value: 'draft',
          label: '草稿'
        },
        {
          value: 'pass',
          label: '审批'
        },
        {
          value: 'reject',
          label: '拒绝'
        },
        {
          value: 'return',
          label: '退回'
        },
        {
          value: 'skipNode',
          label: '跳转'
        }],
      executeTimeLimit: null, // 执行限时
      relationNodeId: '',
      userTaskList: []
    }
  },
  watch: {
    name: {
      handler(newVal, oldVal) {
        this.modeling.updateProperties(this.element, {
          name: newVal
        })
      }
    },

    // 监视元素变化
    element: {
      deep: true,
      immediate: true,
      handler(newVal, oldVal) {
        if (newVal.type === 'bpmn:UserTask') {
          const businessObject = newVal.businessObject
          this.name = businessObject.name
          this.id = businessObject.id
          this.formKey = businessObject.get('formKey') || ''

          this.priority = businessObject.get('priority') || 1

          // 设置初始值
          const bpmnModeler = this.bpmnModeler()
          const bpmnFactory = bpmnModeler.get('bpmnFactory')
          let extensionElements = businessObject.get('extensionElements')

          if (!extensionElements) {
            extensionElements = elementHelper.createElement('bpmn:ExtensionElements', null, this.element, bpmnFactory)
          }
          const length = extensionElements.get('values').length
          let customProperties
          for (let i = 0; i < length; i++) {
            if (extensionElements.get('values')[i] && extensionElements.get('values')[i].$type === 'activiti:CustomProperties') {
              customProperties = extensionElements.get('values')[i]
            }
          }
          if (!customProperties) {
            customProperties = elementHelper.createElement('activiti:CustomProperties', null, this.element, bpmnFactory)
            extensionElements.get('values').push(customProperties)
          }

          const modeling = bpmnModeler.get('modeling')
          modeling.updateProperties(this.element, {
            extensionElements
          })
          // 节点人员方式 0配置，1前端指定
          if (this.getPropertieByName(customProperties, 'assigneeType')) {
            const typeStr = this.getPropertieByName(customProperties, 'assigneeType')
            this.assigneeType = typeStr
          } else {
            this.createOrUpdateCustomProperties('assigneeType', this.assigneeType)
          }

          if (this.getPropertieByName(customProperties, 'relationNodeId')) {
            this.relationNodeId = this.getPropertieByName(customProperties, 'relationNodeId')
            if (this.relationNodeId) {
              this.getUserTaskList()
            }
          } else {
            this.createOrUpdateCustomProperties('relationNodeId', this.relationNodeId)
          }

          if (this.getPropertieByName(customProperties, 'area')) {
            this.area = this.getPropertieByName(customProperties, 'area')
          } else {
            this.createOrUpdateCustomProperties('area', this.area)
          }
          if (this.getPropertieByName(customProperties, 'department')) {
            this.department = this.getPropertieByName(customProperties, 'department')
          } else {
            this.createOrUpdateCustomProperties('department', this.department)
          }
          if (this.getPropertieByName(customProperties, 'role')) {
            const roleStr = this.getPropertieByName(customProperties, 'role')
            // role多选，得用数组
            if (roleStr && roleStr.length > 0) {
              this.role = roleStr.split(',')
            }
          } else {
            this.createOrUpdateCustomProperties('role', this.role)
          }
          if (this.getPropertieByName(customProperties, 'roleIsAnd')) {
            this.roleIsAnd = (this.getPropertieByName(customProperties, 'roleIsAnd') === 'true')
          } else {
            this.createOrUpdateCustomProperties('roleIsAnd', this.roleIsAnd)
          }

          if (this.getPropertieByName(customProperties, 'rule')) {
            this.rule = this.getPropertieByName(customProperties, 'rule')
          } else {
            this.createOrUpdateCustomProperties('rule', this.rule)
          }
          if (this.getPropertieByName(customProperties, 'userType')) {
            this.userType = this.getPropertieByName(customProperties, 'userType')
          } else {
            this.createOrUpdateCustomProperties('userType', this.userType)
          }
          if (this.getPropertieByName(customProperties, 'executeTimeLimit')) {
            this.executeTimeLimit = this.getPropertieByName(customProperties, 'executeTimeLimit')
          } else {
            this.createOrUpdateCustomProperties('executeTimeLimit', this.executeTimeLimit)
          }

          if (this.getPropertieByName(customProperties, 'selectFormKey')) {
            this.selectFormKey = this.getPropertieByName(customProperties, 'selectFormKey')
          } else {
            modeling.updateProperties(this.element, { formKey: this.selectFormKey })
            this.createOrUpdateCustomProperties('selectFormKey', this.selectFormKey)
          }
          // this.createOrUpdateCustomProperties('selectFormKey', this.formKey)

          if (this.getPropertieByName(customProperties, 'formName')) {
            this.formName = this.getPropertieByName(customProperties, 'formName')
          } else {
            this.createOrUpdateCustomProperties('formName', this.formName)
          }

          if (this.getPropertieByName(customProperties, 'proportion')) {
            this.proportion = this.getPropertieByName(customProperties, 'proportion')
          } else {
            this.createOrUpdateCustomProperties('proportion', this.proportion)
          }
          if (this.getPropertieByName(customProperties, 'taskType')) {
            this.taskType = this.getPropertieByName(customProperties, 'taskType')
          } else {
            this.createOrUpdateCustomProperties('taskType', this.taskType)
          }
          if (this.getPropertieByName(customProperties, 'actionList')) {
            this.actionList = this.getPropertieByName(customProperties, 'actionList') || []
          } else {
            this.createOrUpdateCustomProperties('actionList', this.actionList.join(',') || '')
          }
        }
      }
    },
    assigneeType: {
      handler(newVal, oldVal) {
        this.createOrUpdateCustomProperties('assigneeType', newVal)
      }
    },
    relationNodeId: {
      handler(newVal, oldVal) {
        this.createOrUpdateCustomProperties('relationNodeId', newVal)
      }
    },
    area: {
      handler(newVal, oldVal) {
        this.createOrUpdateCustomProperties('area', newVal)
      }
    },
    department: {
      handler(newVal, oldVal) {
        this.createOrUpdateCustomProperties('department', newVal)
      }
    },
    role: {
      handler(newVal, oldVal) {
        this.createOrUpdateCustomProperties('role', newVal)
      }
    },
    roleIsAnd: {
      handler(newVal, oldVal) {
        this.createOrUpdateCustomProperties('roleIsAnd', newVal)
      }
    },
    rule: {
      handler(newVal, oldVal) {
        this.createOrUpdateCustomProperties('rule', newVal)
      }
    },
    userType: {
      handler(newVal, oldVal) {
        this.createOrUpdateCustomProperties('userType', newVal)
      }
    },
    executeTimeLimit: {
      handler(newVal, oldVal) {
        this.createOrUpdateCustomProperties('executeTimeLimit', newVal)
      }
    },
    selectFormKey: {
      handler(newVal, oldVal) {
        this.modeling.updateProperties(this.element, { formKey: newVal })
        this.createOrUpdateCustomProperties('selectFormKey', newVal)
      }
    },
    formName: {
      handler(newVal, oldVal) {
        this.createOrUpdateCustomProperties('formName', newVal)
      }
    },
    taskType: {
      handler(newVal, oldVal) {
        this.createOrUpdateCustomProperties('taskType', newVal)
      }
    },

    proportion: {
      handler(newVal, oldVal) {
        this.createOrUpdateCustomProperties('proportion', newVal)
      }
    },
    actionList: {
      handler(newVal, oldVal) {
        console.log('watch actionList:' + newVal)
        this.createOrUpdateCustomProperties('actionList', newVal)
      }
    },
    priority: {
      handler(newVal, oldVal) {
        this.modeling.updateProperties(this.element, { priority: newVal })
      }
    },
    candidateGroups: {
      handler(newVal, oldVal) {
        this.modeling.updateProperties(this.element, { candidateGroups: newVal })
      }
    },
    candidateUsers: {
      handler(newVal, oldVal) {
        this.modeling.updateProperties(this.element, { candidateUsers: newVal })
      }
    },
    assignee: {
      handler(newVal, oldVal) {
        this.modeling.updateProperties(this.element, { assignee: newVal })
      }
    }

  },
  mounted() {
    const bpmnModeler = this.bpmnModeler()
    this.modeling = bpmnModeler.get('modeling')
  },
  created() {
    this.getNodeAction()
    this.getAreaAction()
    this.getDepartmentAction()
    this.getRoleAction()
    this.getRuleAction()
  },
  methods: {
    getAreaValue(e) {
      this.area = e
    },
    getDeptValue(e) {
      this.department = e
    },
    handleChange() {
      const actionList = this.actionList || []
      const actionArray = []
      const tempActionArray = []
      this.actionTypeList.forEach((item, index) => {
        actionArray.push(item.value)
      })
      actionList.forEach((item, index) => {
        console.log('item:' + item)
        if (actionArray.join(',').indexOf(item) > -1) {
          tempActionArray.push(item)
        }
      })
      this.actionList = tempActionArray
      console.log(this.actionList)
    },
    getNodeAction() {
      // 获取节点动作
      const param = 'pig:dict:nodeAction'
      const that = this
      this.$emit('getNodeAction', param, val => {
        that.actionTypeList = val
      }) // 传函数给父组件
      console.log('usertask调用了getNodeAction')
    },
    getAreaAction() {
      // 获取区域动作
      const that = this
      this.$emit('getAreaAction', val => {
        that.areaList = val
      }) // 传函数给父组件
      console.log('usertask调用了getAreaAction')
    },
    getDepartmentAction() {
      // 获取部门动作
      const that = this
      this.$emit('getDepartmentAction', val => {
        that.departmentList = val
      }) // 传函数给父组件
      console.log('usertask调用了getDepartmentAction')
    },
    getRoleAction() {
      // 获取角色动作
      const that = this
      this.$emit('getRoleAction', val => {
        that.roleList = val
      }) // 传函数给父组件
      console.log('usertask调用了getRoleAction')
    },
    getRuleAction() {
      // 获取规则动作
      const that = this
      this.$emit('getRuleAction', val => {
        that.ruleList = val
      }) // 传函数给父组件
      console.log('usertask调用了getRuleAction')
    },
    getPropertieByName(customProperties, name) {
      return customProperties.get(name) || customProperties.$attrs[name]
    },
    getUserTaskList() {
      const that = this
      const nodeList = []
      try {
        for (const index in that.bpmnModeler()._definitions.$model.ids._seed.hats) {
          if (that.bpmnModeler()._definitions.$model.ids._seed.hats[index].$type !== 'bpmn:UserTask') continue
          if (this.id === that.bpmnModeler()._definitions.$model.ids._seed.hats[index].id) continue
          nodeList.push({
            value: that.bpmnModeler()._definitions.$model.ids._seed.hats[index].id,
            label: that.bpmnModeler()._definitions.$model.ids._seed.hats[index].name
          })
        }
      } catch (e) {
        console.error(e)
      }
      this.userTaskList = nodeList
    },
    setForm(formKey, formName) {
      this.formKey = formKey
      this.formName = formName
      this.closeSelectFormDialog()
    },

    showSelectDialog() {
      this.selectFormDialog.visible = true
    },
    closeSelectFormDialog() {
      this.selectFormDialog.visible = false
    },

    handleClose(done) {
      this.$confirm(this.$t('action.confirmClose'))
        .then(_ => {
          done()
        })
        .catch(_ => { })
    },
    remove(array, val) {
      const index = array.indexOf(val)
      if (index > -1) {
        array.splice(index, 1)
      }
    },

    updateDocumentation(value) {
      bpmnHelper.updateDocumentation(this.bpmnModeler(), this.element, value)
    },
    createOrUpdateCustomProperties(property, value) {
      if (property === 'assigneeType' && value === '2') {
        this.getUserTaskList()
      }
      const that = this
      const bpmnModeler = that.bpmnModeler()
      const bpmnFactory = bpmnModeler.get('bpmnFactory')
      let extensionElements = bpmnHelper.getPropertie(that.element, 'extensionElements')
      if (!extensionElements) {
        extensionElements = elementHelper.createElement('bpmn:ExtensionElements', null, this.element, bpmnFactory)
      }
      const length = extensionElements.get('values').length
      let customProperties
      let customPropertiesIndex = -1
      for (let i = 0; i < length; i++) {
        if (extensionElements.get('values')[i] && extensionElements.get('values')[i].$type === 'activiti:CustomProperties') {
          customProperties = extensionElements.get('values')[i]
          customPropertiesIndex = i
        }
      }
      if (!customProperties) {
        customProperties = elementHelper.createElement('activiti:CustomProperties', null, this.element, bpmnFactory)
      }

      const data = {}
      data[property] = value
      customProperties[property] = value
      if (customPropertiesIndex > -1) {
        extensionElements.get('values')[customPropertiesIndex] = customProperties
      } else {
        extensionElements.get('values').push(customProperties)
      }
      const modeling = bpmnModeler.get('modeling')
      modeling.updateProperties(this.element, {
        extensionElements
      })
    }
  }

}
</script>
<style>
</style>
